//
// Created by 27411 on 2025/11/7.
//
#include "backend_admin.h"

void clear_input_buffer() {
    int c;
    while ((c = getchar()) != '\n' && c != EOF);
}



int backend_admin_login() {
        Admin admin;
        memset(&admin, 0, sizeof(Admin));

        printf("------------------- 管理员登录 -------------------\n");
        printf("输入管理员账号: ");
        if (scanf("%49s", admin.account) != 1) {
            printf("输入格式错误!\n");
            clear_input_buffer();
            return -1;
        }
        clear_input_buffer();

        printf("输入密码: ");
        if (scanf("%19s", admin.password) != 1) {
            printf("输入格式错误!\n");
            clear_input_buffer();
            return -1;
        }
        clear_input_buffer();

        const char *sql = "SELECT password FROM admin_user WHERE account = ?";
        sqlite3_stmt *stmt = NULL;
        int rc = sqlite3_prepare_v2(db, sql, -1, &stmt, NULL);
        if (rc != SQLITE_OK) {
            fprintf(stderr, "SQL 编译出错: %s\n", sqlite3_errmsg(db));
            sqlite3_finalize(stmt);
            return -1;
        }

        sqlite3_bind_text(stmt, 1, admin.account, -1, SQLITE_TRANSIENT);
        rc = sqlite3_step(stmt);

        if (rc != SQLITE_ROW) {
            // 账号不存在
            printf("登录失败：账号不存在或密码错误！\n");
            sqlite3_finalize(stmt);
            return -1;
        }

        const char *db_password = (const char *)sqlite3_column_text(stmt, 0);
        if (db_password == NULL || strcmp(admin.password, db_password) != 0) {
            // 密码错误
            printf("登录失败：账号不存在或密码错误！\n");
            sqlite3_finalize(stmt);
            return -1;
        }

        sqlite3_finalize(stmt);
        return 0; // 登录成功
    }

void admin_login_menu() {
    while (1) { // 无限循环，直到登录成功
        int login_result = backend_admin_login();
        if (login_result == 0) {
            // 登录成功，跳出循环
            printf("登录成功！正在进入后台管理系统...\n");
            break;
        } else {
            // 登录失败，提示用户重新尝试
            printf("请重新输入。\n");
        }
    }
}